package com.sj.purchase.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 上传文件到七牛云
 * 账号:18364512960@163.com
 * 密码:qwezxc123
 * <p>
 * Create By MaJinGe on 2017-12-02
 */
public class QiNiuUtil {

    /**
     * 基本配置-从七牛管理后台拿到
     */
    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static String ACCESS_KEY = "ohzlGtXsXZhXPjqlkBPq734upPcHxZGc4jYgh8gM";
    private static String SECRET_KEY = "6JfVA1h4Li_m6u5t7L-il3aSTAXu0YSVkOPp1WFz";
    //要上传的空间名--
    private static String bucketname = "excelbysj";

    //密钥配置
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //创建上传对象
    private static UploadManager uploadManager = new UploadManager(new Configuration());

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    private static String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    private static String filePath;
    private static String fileName;

    /**
     * 文件上传
     *
     * @param filePath
     * @param fileName
     */
    public static void uploadByFile(String filePath, String fileName) {
        /**指定保存到七牛的文件名--同名上传会报错  {"error":"file exists"}*/
        /** {"hash":"FrQF5eX_kNsNKwgGNeJ4TbBA0Xzr","fileName":"aa1.jpg"} 正常返回 key为七牛空间地址 http:/xxxx.com/aa1.jpg */
        //上传文件的路径
        QiNiuUtil.filePath = filePath;
        //上传到七牛后保存的文件名    访问为：http://oswj11a86.bkt.clouddn.com/demo1.xls
        QiNiuUtil.fileName = fileName;
        try {
            //调用put方法上传
            Response res = uploadManager.put(QiNiuUtil.filePath, QiNiuUtil.fileName, getUpToken());
            //打印返回的信息
            System.out.println("状态码:" + res.statusCode + "-->上传成功");//200为上传成功
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
    }

    /**
     * 流式上传
     */
    public static void uploadByByte(ByteArrayInputStream byteInputStream, String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
//...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        String upToken = auth.uploadToken(bucketname);
        try {
            Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println("上传成功 => "+putRet.key);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    public static String getFilePath() {
        return filePath;
    }

    public static String getFileName() {
        return fileName;
    }

    /**
     * 下载文件
     *
     * @throws IOException
     */
    public static void downLoadFromUrl(String fileName) {
        try {
            URL url = new URL("http://p0bm6djbo.bkt.clouddn.com/" + fileName + "订单详情.xls");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);

            //文件保存位置
            File saveDir = new File("D:/三际进存销报表");
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName + "订单详情.xls");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            System.out.println("info:" + url + " download success");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}
